############################################
###### Replication Code for Figure A5 ######
########### January 9th, 2025 ##############
############################################

### Script produces Figure A5 and saves it in the `/figures` folder

rm(list=ls())

######## Load Data
library(fixest)
library(modelsummary)
library(dplyr)
library(ggplot2)

# load data
df_main <- readRDS("data/workfile.rds")


###### By county
country_names <- unique(df_main$dem_country_code)
coef_df_main <- data.frame()

for(i in country_names){
  
  
  ###### Treatments effects by condition
  df <- df_main %>%
    filter(dem_country_code != i) %>% 
    group_by(dem_country_code) %>% 
    mutate(trust_in_opposing_parties2 = scale(trust_in_opposing_parties))
  df$trust_in_opposing_parties <- scale(df$trust_in_opposing_parties)
  
  coef_df <- data.frame()
  
  trust_no_cov <- feols(trust_in_opposing_parties ~ treated_econ + treated_culture, df, se = "iid") %>% 
    summary()
  trust_cts_fe <- feols(trust_in_opposing_parties ~ treated_econ + treated_culture  | dem_country_code, df, se = "iid") %>% 
    summary()
  trust_cov_adj <- feols(trust_in_opposing_parties ~ treated_econ + treated_culture + 
                           mean_outparty_feeling + high_pol_interest | dem_country_code, df, se = "iid") %>% 
    summary()
  
  coef_df <- data.frame(coef = c(trust_no_cov$coefficients[2:3], trust_cts_fe$coefficients[1:2], trust_cov_adj$coefficients[1:2]), 
                        se = c(trust_no_cov$se[2:3], trust_cts_fe$se[1:2], trust_cov_adj$se[1:2]),
                        name = rep(c("Economic issues \n condition", "Cultural issues \n condition"), times = 3),
                        var = rep(c("No covariates", "Country-FE", "Country-FE + covariate adj."), each = 2), 
                        country = i)
  
  
  coef_df_main <- rbind.data.frame(coef_df_main, coef_df)
}

pd <- position_dodge(0.5)

coef_df_main <- coef_df_main %>% filter(var == "Country-FE + covariate adj.")

regs <- ggplot(coef_df_main, aes(x = country,y = coef, shape = var, color = name)) + 
  ylim(c(-0.15, 0.05)) +
  geom_point(position = pd, shape = 21, fill = 'white') + 
  geom_errorbar(aes( ymin = coef - se*1.959964, ymax = coef + se*1.959964), width = 0, position = pd) + 
  geom_errorbar(aes( ymin = coef - se*1.644854, ymax = coef + se*1.644854), width = 0, position = pd, linewidth = 1.5) + 
  geom_hline(yintercept = 0, color = "red", linetype = "dashed") +
  scale_colour_manual(values = c("black", "grey", "darkorange")) + 
  xlab("") + 
  ylab("Treatment effect on out-partisan trust") +
  coord_flip() +
  #facet_wrap(~ var) + 
  theme_bw() + 
  guides(color=guide_legend(title=""))
regs

ggsave("figures/FigA5_agg_treatments_l1out.pdf", 
       height = 4, width = 6)



